var rldMap = null;//风险级别字典
/**
 * 通知管理初始化
 */
var PatienList = {
    id: "patientListTable",	//表格id
    seItem: null,		//选中的条目
    table: null,
    layerIndex: -1
};

/**
 * 初始化表格的列
 */
PatienList.initColumn = function () {
    var columnArr =  [
        {title: '当前科室', field: 'curDept', align: 'center', width:100,valign: 'middle', sortable: false},
        {title: '姓名', field: 'caseName', align: 'center', width:70, valign: 'middle', sortable: false},
        {title: '病案号', field: 'caseMrno', align: 'center', width:80,valign: 'middle', sortable: false},
        {title: '性别', field: 'caseSex', align: 'center', width:50, valign: 'middle', sortable: false},
        {title: '年龄', field: 'caseAge', align: 'center', width:50, valign: 'middle', sortable: false},
        {title: '主治医生', field: 'docName', align: 'center', width:70, valign: 'middle', sortable: false},
        {title: '就诊病区', field: 'curWard', align: 'center', width:100, valign: 'middle', sortable: false},
        {title: '床位号', field: 'bedCode', align: 'center', width:90, valign: 'middle', sortable: false},
        {title: '入院日期', field: 'admDate', align: 'center', width:160,valign: 'middle', sortable: false},
        {title: '质控病种', field: 'entityName', align: 'center', width:110,valign: 'middle', sortable: false},
        {title: '操作', field: 'id', align: 'center', width: 80, valign: 'middle',formatter:function(value,row,index){
                var _html = '';
                if (row.state == "已确认"){
                    //已入组
                    _html += '<a href="javascript:PatienList.del(\''+row.mrListId+'\',\''+row.entityId+'\')" title="排除"><i class="hisui-icon icon-cancel"></i></a>';
                    // _html += '<a href="javascript:SdsMedicalGroup.up(\''+row.qcincaseId+'\',\''+row.name+'\')" title="上报"><i class="hisui-icon icon-upload-cloud"></i></a>';
                } else {
                    //未入组 和 已排除
                    _html = '<a href="javascript:PatienList.inGroup(\''+row.episodeId+'\')" title="入组"><i class="hisui-icon icon-add-item"></i></a>';
                }
                return _html;
            }
        }
    ];
    return columnArr;
};

/**
 * 删除病种入组病例
 */
PatienList.del = function (id,entityId) {
    var flag = false;
    if (id) {
        flag = true;
    } else if (this.check()) {
        id = this.seItem.id;
        entityId = this.seItem.entityId;
        flag = true;
    }
    if (flag) {
        //打开 弹出框
        var index = layer.open({
            type: 2,
            title: ['排除单病种【信息录入】'],
            area: ['600px', '400px'],
            zIndex: 19911102,//这是个大坑！！！！ 默认是19891014 远远大于量表下拉框的zIndex 导致下拉框的数据看不到！！！
            content: Sys.backendPath + "/sdc/case/outputMr?mrListId=" + id + "&entityId=" + entityId,
            skin: 'layer-ext-hisui',
            scrollbar: false//为了禁止父页面滚动条滚动
        });
        this.layerIndex = index;

        //监听子页面的postMessage
        function receiveMessage(event) {
            //取得子页面传回来的值
            if (event.data == "close") {
                // 如果传回close，关闭当前弹窗
                layer.close(index);
            }
            if (event.data == "save") {
                PatienList.table.refresh();
                setTimeout(function () {
                    layer.close(index);
                }, 1000);
            }
        }
        window.addEventListener('message', receiveMessage, false);
    }
};

/**
 * 检查是否选中
 */
PatienList.check = function () {
    var selected = $('#' + this.id).bootstrapTable('getSelections');
    if(selected.length == 0){
        Sys.info("请先选中表格中的某一记录！");
        return false;
    }else{
        PatienList.seItem = selected[0];
        return true;
    }
};

/**
 * 入组
 */
PatienList.inGroup = function (id) {
    var flag = false;
    if (id) {
        flag = true;
    } else if (this.check()) {
        id = this.seItem.id;
        flag = true;
    }
    if (flag) {
        var index = layer.open({
            type: 2,
            title: '入单病种管理',
            area: ['420px', '280px'], //宽高
            fix: false, //不固定
            content: '/sdc/case/in_group/' + id,
            cancel: function (index, layero) {
                layer.close(index);
                PatienList.table.refresh();
                return false;
            }
        });
        this.layerIndex = index;
        //监听子页面的postMessage
        function receiveMessage(event) {
            //取得子页面传回来的值
            if (event.data == "close") {
                // 如果传回close，关闭当前弹窗
                layer.close(index);
            }
            if (event.data == "save") {
                PatienList.table.refresh();
                setTimeout(function () {
                    layer.close(index);
                }, 1000);
            }
        }
        window.addEventListener('message', receiveMessage, false);
    }
};
/**
 * 导出数据-不同条件
 */
PatienList.exportExcel = function (){

    var startDate = $('#startDate').datebox('getValue');
    var endDate = $('#endDate').datebox('getValue');
    var queryData = {};
    queryData['qcStatus'] = $('#qcStatus').datebox('getValue');    //统计类型
    queryData['startDate'] = startDate;    //获取页面开始时间
    queryData['endDate'] = endDate;    //获取页面结束时间
    queryData['office'] = $('#office').datebox('getValue');//部门
    queryData['depart'] = $('#depart').datebox('getValue');//科室
    queryData['entityType'] = $('#entityType').datebox('getValue');//病种类别
    // queryData['mrListId'] = $('#mrListId').datebox('getValue');//入组记录ID
    queryData['entityId'] = $('#entityType').datebox('getValue');//病种ID
    queryData['state'] = $('#qcStatus').datebox('getValue');//当前入组状态


    if(queryData['startDate']!=""){
        queryData['startDate'] = queryData['startDate'] + " 00:00:00";
    }
    if(queryData['endDate']!=""){
        queryData['endDate'] = queryData['endDate'] + " 23:59:59";
    }
    var longStart = Date.parse(startDate);
    var longEnd = Date.parse(endDate);
    if(longStart>longEnd){
        Sys.error("开始日期不可大于结束日期");
        return false;
    }

    Sys.loading("数据文件生成中,请耐心等待");
    var ajax = new $ax(Sys.backendPath + "/sdc/case/createExcel", function(data){
        Sys.closeLoading();
        if(data.message=="DHCC"){
            Sys.info("无数据可以导出，请更改查询条件。");
        }else{
            window.location.href = Sys.backendPath + "/sdc/case/excelDown/"+data.message;
            PatienList.table.refresh();
        }
    },function(data){
        Sys.error("数据生成失败!" + data.responseJSON.message + "!");
    });
    ajax.set(queryData);
    ajax.setAsync(true);
    ajax.start();
}

/**
 * 查询病例
 */
PatienList.search = function (){
    var startDate = $('#startDate').datebox('getValue');
    var endDate = $('#endDate').datebox('getValue');
    var queryData = {};
    queryData['qcStatus'] = $('#qcStatus').datebox('getValue');    //统计类型
    queryData['startDate'] = startDate;    //获取页面开始时间
    queryData['endDate'] = endDate;    //获取页面结束时间
    queryData['office'] = $('#office').datebox('getValue');//部门
    queryData['xcode'] = $('#xcode').val();//就诊号
    queryData['name'] = $('#name').val();//患者姓名
    queryData['mrNum'] = $('#mrNum').val();//病案号
    queryData['docName'] = $('#docName').val();//主治医生
    queryData['depart'] = $('#depart').datebox('getValue');//科室
    queryData['entityType'] = $('#entityType').datebox('getValue');//患者类别

    if(queryData['startDate']!=""){
        queryData['startDate'] = queryData['startDate'] + " 00:00:00";
    }
    if(queryData['endDate']!=""){
        queryData['endDate'] = queryData['endDate'] + " 23:59:59";
    }
    var longStart = Date.parse(startDate);
    var longEnd = Date.parse(endDate);
    if(longStart>longEnd){
        Sys.error("开始日期不可大于结束日期");
        return false;
    }
    PatienList.table.refresh({query: queryData,pageNumber: 1});
}

/**
 * //根据父级机构 查询子机构
 */
PatienList.officeChange = function(that){
    var ajax = new $ax(Sys.backendPath + "/sds/common/deptListByHospId", function(data){
        $('#depart').combobox({
            data:data,
            valueField:'value',
            textField:'text',
            defaultFilter: 6,
            onLoadSuccess: function () { //加载完成后,val[0]写死设置选中第一项
                $(this).combobox("setValue", "");
            }
        });
    },function(data){
        layer.msg("查询失败!" + data.responseJSON.message + "!",{icon: 2});
    });
    ajax.set({"hospID":that.value,"id":"depart"});
    ajax.start();
}


$(function () {
    //科室
    $('#depart').combobox({
        data:$.parseJSON($("#departMap").val()),
        valueField:'value',
        textField:'text'
    });
    //院区
    $('#office').combobox({
        data:$.parseJSON($("#officeMap").val()),
        valueField:'value',
        textField:'text',
        defaultFilter: 6,
        onSelect:PatienList.officeChange,
        onLoadSuccess: function () {
            var hospId = $('#hospitalId').val();
            if (hospId != "") {
                $(this).combobox("setValue", hospId);
                $(this).combobox('disable');
            } else {
                //加载完成后,val[0]写死设置选中第一项
                var val = $(this).combobox("getData");
                if (val.length == 2) {//如果就一个院区 加上全部=2
                    $(this).combobox("setValue", val[1].value);
                    PatienList.officeChange(val[1]);
                } else {
                    $(this).combobox("setValue", "");
                }
            }
        }
    });
    //病种
    $('#entityType').combobox({
        data:$.parseJSON($("#entityMap").val()),
        valueField:'value',
        textField:'text',
        defaultFilter: 6
    });
    // 状态
    $('#qcStatus').combobox({
        data:[
            {value:"",text:"全部"},
            {value:"Y",text:"已入组"},
            {value:"N",text:"未入组"},
        ],
        valueField:'value',
        textField:'text',
        defaultFilter: 6
    });
    //渲染datebox --没有渲染的话 图标左右间距不等
    $('.hisui-datebox').datebox({});

    //默认365天
    $('#startDate').datebox('setValue', timeStamp2String(new Date().getTime()-(1000 * 60 * 60 * 24*365)));
    $('#endDate').datebox('setValue', timeStamp2String(new Date().getTime()));

    var startDate = $('#startDate').datebox('getValue');//开始日期
    var endDate = $('#endDate').datebox('getValue');//结束日期
    startDate = startDate + " 00:00:00";
    endDate = endDate + " 23:59:59";
    var qcStatus = $('#qcStatus').combobox('getValue');
    var entityType = $('#entityType').combobox('getValue');
    var defaultColunms = PatienList.initColumn();
    var table = new BSTable(PatienList.id, Sys.backendPath + "/sdc/case/list", defaultColunms);
    // table.setResizable(true);
    table.setPaginationType("server");
    table.setQueryParams({qcStatus:qcStatus,entityType:entityType,startDate:startDate,endDate:endDate,office:'',depart:''});
    table.setShowColumns(false);
    table.setShowRefresh(false);
    table.setShowToggle(false);
    table.setPageSize(15);
    table.setSubHeight(-27);

    PatienList.table = table.init();
    table.refresh()
});


//在Jquery里格式化Date日期时间数据
function timeStamp2String(time){
    var datetime = new Date();
    datetime.setTime(time);
    var year = datetime.getFullYear();
    var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
    var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
    return year + "-" + month + "-" + date;
}